package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //通过用户名字返回用户信息
        User user = userDao.findByUsername(username);
        //判断用户是否存在
        if (user == null) {
            return null;
        }
        //根据用户id获取相关角色
        Set<Role> roles = roleDao.findByUserId(user.getId());
        //判断是否有角色
        if (roles != null || roles.size() > 0) {
            //循环
            for (Role role : roles) {
                //根据角色id获取相应的权限信息
                Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                //判断是否有权限
                if (permissions != null || permissions.size() > 0) {
                    //存入
                    role.setPermissions(permissions);
                }
            }
            //存入
            user.setRoles(roles);
        }
        //返回user
        return user;
    }
}
